package com.lj.common_web.config;

import cn.hutool.core.util.ArrayUtil;
import com.lj.common_web.filter.SignFilter;
import com.lj.common_web.filter.VerifySignature;
import com.lj.common_web.properties.SignProperties;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Resource
    private SignProperties signProperties;

    /**
     * 设置跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 所有接口
                .allowCredentials(true) // 是否发送 Cookie
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 支持方法
                .allowedHeaders("*")
                .maxAge(3600);
    }

    @Bean
    @ConditionalOnBean(VerifySignature.class)
    public FilterRegistrationBean<SignFilter> customFilter(VerifySignature verifySignature) {
        FilterRegistrationBean<SignFilter> registrationBean = new FilterRegistrationBean<>();

        registrationBean.setFilter(new SignFilter(verifySignature));
        // 拦截的请求
        String[] urlPatterns = signProperties.getUrlPatterns();
        if (ArrayUtil.isEmpty(urlPatterns)) {
            throw new RuntimeException("没有配置需要签名的url资源 如果所有接口都需要签名可以配置为: /**");
        }
        registrationBean.addUrlPatterns(urlPatterns);
        // 设置执行顺序(数字越小优先级越高)
        registrationBean.setOrder(signProperties.getOrder());
        return registrationBean;
    }

}